package com.liuxu.topnews.acitivity;

import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.liuxu.topnews.Adapter.Recycle_Home_Adapter;
import com.liuxu.topnews.BuildConfig;
import com.liuxu.topnews.MyApplication;
import com.liuxu.topnews.R;
import com.liuxu.topnews.Manager.Service;
import com.liuxu.topnews.Manager.UpdateManager;
import com.liuxu.topnews.floating.FloatingManager;
import com.liuxu.topnews.service.FloatWindowService;
import com.liuxu.topnews.service.ReadService;
import com.liuxu.topnews.utils.MultiUtils;
import com.liuxu.topnews.utils.ShareUtil;
import com.liuxu.topnews.utils.ToastUtils;
import android.widget.ArrayAdapter;

import static com.liuxu.topnews.MyApplication.checkBoxList;
import static com.liuxu.topnews.MyApplication.float_window;
import static com.liuxu.topnews.MyApplication.globalapps;
import static com.liuxu.topnews.MyApplication.permission;
import static com.liuxu.topnews.MyApplication.random_read;
import static com.liuxu.topnews.MyApplication.video_read;


public class HomeFragment extends Fragment {
//
    public boolean check=true;
    public static int version;
    private int index;
    public Button button1;
    public Button button2;
    public Button button3;
//    public Button button4;
    public Switch switch1;
    public Switch switch2;
    public Switch switch3;
    public Switch switch4;
    public Switch switch5;
    public Spinner spinnerCardNumber;
    public EditText editText1;
    public EditText editText2;
    public View view;
    public MainActivity parentActivity;
    public Intent readintent;
    public Intent floatintent;
    public Recycle_Home_Adapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        switch (BuildConfig.version) {
            case "normal":
                view = inflater.inflate(R.layout.home_fragment, container, false);
                break;
            case "hw":
                view = inflater.inflate(R.layout.home_fragment_hw, container, false);
                break;
            case "xm":
                view = inflater.inflate(R.layout.home_fragment_hw, container, false);
                break;
            default:
                view = inflater.inflate(R.layout.home_fragment, container, false);
                break;
        }
        parentActivity= (MainActivity ) getActivity();
        initView();
        initListener();

        return view;
    }
    private void initView() {
        button1 = (Button)view.findViewById(R.id.button1);
        button2 = (Button)view. findViewById(R.id.button2);
        button3 = (Button)view. findViewById(R.id.button3);
//        button4 = (Button)view. findViewById(R.id.button4);
        switch1=(Switch)view.findViewById(R.id.switch1);
        switch2=(Switch)view.findViewById(R.id.switch2);
        switch3=(Switch)view.findViewById(R.id.switch3);
        switch4=(Switch)view.findViewById(R.id.switch4);
        switch5=(Switch)view.findViewById(R.id.switch5);
        RecyclerView recyclerView= (RecyclerView)view.findViewById(R.id.homeapplist_view);
        MultiUtils.getInstance().initAppData(true);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(MyApplication.getContext(), 3);
        recyclerView.setLayoutManager(gridLayoutManager);
        adapter=new Recycle_Home_Adapter();
        recyclerView.setAdapter(adapter);
        spinnerCardNumber = (Spinner)view.findViewById(R.id.spinner1);
        editText1 =(EditText)view.findViewById(R.id.word);
        editText2 =(EditText)view.findViewById(R.id.index);
        ShareUtil.getInstance().tokenSet(editText1);
        ShareUtil.getInstance().swithcSet(switch1,switch2,switch3,switch4,switch5);
        TextView visiontext =(TextView)view.findViewById(R.id.TextView11);
        version =MainActivity.getVersionCode(MyApplication.getContext());
        String versionname=MainActivity.getVersion(MyApplication.getContext());
        visiontext.setText("版本号："+ versionname+"  标识符："+BuildConfig.tokenhead);
        readintent = new Intent(MyApplication.getContext(), ReadService.class);
        floatintent= new Intent(MyApplication.getContext(), FloatWindowService.class);
        parentActivity.startService(floatintent);
    }
    private void initListener() {

//        button4.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                FloatingManager.getInstance().show();
//            }
//        });
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for(int i=0;i<checkBoxList.size();i++){
                    globalapps.get(i).setCheck(check);
                    checkBoxList.get(i).setChecked(check);
                }
                check=!check;
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("begin", "onDestroy");
                    System.exit(0);
//                MyApplication.permission = false;
//                try{
//                    ReadService.getInstance().stop();
////                    getActivity().stopService(readintent);
//                }catch (Exception e){
//                    e.printStackTrace();
//                    ToastUtils.getInstance().shownow("阅读未运行");
//                }
            }
        });
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    run();
            }
        });
        switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                MyApplication.sleep=switch1.isChecked();
                if (switch1.isChecked()){
                    Log.e("凌晨休息功能", "打开");
                    Toast.makeText(MyApplication.getContext(),"启用休息功能",Toast.LENGTH_SHORT).show();
                }else {
                    Log.e("凌晨休息功能", "关闭");
                    Toast.makeText(MyApplication.getContext(),"关闭休息功能",Toast.LENGTH_SHORT).show();
                }
            }
        });
        switch2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                MyApplication.autoclear=switch2.isChecked();
                if (switch2.isChecked()){
                    Log.e("阅读数据0点自动重置", "打开");
                    ToastUtils.getInstance().shownow("启用阅读数据0点自动重置");
                }else {
                    Log.e("阅读数据0点自动重置", "关闭");
                    ToastUtils.getInstance().shownow("启用阅读数据0点自动重置");
                }
            }
        });
        switch3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                random_read=switch3.isChecked();
                if (switch3.isChecked()){
                    Log.e("随机阅读", "启用");
                    Toast.makeText(MyApplication.getContext(),"启用随机阅读功能",Toast.LENGTH_SHORT).show();
                }else {
                    Log.e("随机阅读", "关闭");
                    Toast.makeText(MyApplication.getContext(),"关闭随机阅读功能",Toast.LENGTH_SHORT).show();
                }
            }
        });
        switch4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                video_read=switch4.isChecked();
                if (switch4.isChecked()){
                    Log.e("看视频", "启用");
                    Toast.makeText(MyApplication.getContext(),"不看视频省流量",Toast.LENGTH_SHORT).show();
                }else {
                    Log.e("看视频", "关闭");
                    Toast.makeText(MyApplication.getContext(),"视频也看多赚金币",Toast.LENGTH_SHORT).show();
                }
            }
        });
        switch5.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                float_window=switch5.isChecked();
                if (switch5.isChecked()){
                    Log.e("悬浮窗", "打开");
//                    ActivityCompat.requestPermissions(parentActivity, new String[]{Manifest.permission.SYSTEM_ALERT_WINDOW}, 3);
                    FloatingManager.getInstance().show();
                    Toast.makeText(MyApplication.getContext(),"如未出现悬浮窗也未弹出权限申请，请设置手动设置权限",Toast.LENGTH_SHORT).show();
                }else {
                    Log.e("悬浮窗", "关闭");
                    FloatingManager.getInstance().remove();
                }
            }
        });

    }
    public void run(){

        permission=false;
        String action =spinnerCardNumber.getSelectedItem().toString();
        String token=editText1.getText().toString();
        if (token.equals("")){
            ToastUtils.getInstance().shownow("请输入注册码！");
            return;
        }
        if (!token.substring(0,1).equals(BuildConfig.tokenhead)&&action.equals("注册")){
            ToastUtils.getInstance().shownow("注册卡类型错误");
            return;
        }
        String id=parentActivity.getSerial();
        ShareUtil.getInstance().tokenSave(token);
        ShareUtil.getInstance().CheckSave();
        ShareUtil.getInstance().swithcSave(switch1,switch2,switch3,switch4,switch5);
        Service service=new Service();
        service.checkUpdate(version);
        if (MyApplication.updateCheck&&MyApplication.update){
            UpdateManager updateManager=new UpdateManager();
            updateManager.mContext=getContext();
            updateManager.showNoticeDialog();
            if (MyApplication.must){
                Toast.makeText(MyApplication.getContext(),"此版本为强制更新",Toast.LENGTH_LONG).show();
            }
        }else if (id==null) {
            Toast.makeText(MyApplication.getContext(),"权限不足",Toast.LENGTH_SHORT).show();
        }else {
            if(parentActivity.checkAccessibilityEnabled(BuildConfig.APPLICATION_ID+"/com.liuxu.topnews.service.AccessService")){
                service.run(version,action,token,id,parentActivity.handler);
                MyApplication.updateCheck=true;
                try{
                    index=Integer.parseInt(editText2.getText().toString());
                }catch (Exception e){
                    index=0;
                    ToastUtils.getInstance().shownow("使用默认配置，从第一个开始阅读");
                }
                readintent.putExtra("index",index);
                if (permission){
                    parentActivity.startService(readintent);//启动servicce服务
                }
            }else{
                Intent Settingintent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
                startActivity(Settingintent);
                Toast.makeText(MyApplication.getContext(),"请找到"+BuildConfig.appname+"并打开所属服务",Toast.LENGTH_LONG).show();
            }
        }
    }

}
